import { userData } from "@/store/userData";
import { advanceOrder,makeOrder,checkPayStatu } from "@/api/api";
import {showLoading,closeLoading} from '@/utils/utils'

const wait = (time:number)=>{
    return new Promise((resolve, reject)=>{
        if(!time){
            resolve(true)
        }else{
            setTimeout(()=>{
                resolve(true)
            },time)
        }
        
    })
}



const state:any = {
    slimType:null, //  1 开会员  2 入群
    totalAmt:null, // 金额
    productId:null, // 入群时为群id,
    preId:null,
    orderId:'',
    payType:null,
    checkNum:0,
    chancel:false,
    webview:null,
}

const init = ()=>{
    state.slimType = null;
    state.totalAmt = null;
    state.productId = null;
    state.preId = null;
    state.orderId = '';
    state.payType = null;
    state.checkNum = 0;
    state.chancel = false;
    state.webview = null;
}


const AdvanceOrder = async()=>{

    const USER_DATA = userData();

    const params = {
        userId:USER_DATA.id,
        slimType:Number(state.slimType),
        totalAmt:Number(state.totalAmt),
        productId:state.productId,
    }

    const res:any = await advanceOrder(params);
    const {flag,message} = res;
    if(flag!==1){
        uni.showToast({
            icon: "none",
            title: message,
            duration: 3000,
        });
        closeLoading();
        return 
    }

    console.log('advanceOrder')
    console.log('advanceOrder')
    console.log('advanceOrder')
    console.log('advanceOrder')
    console.log(res);

    state.preId = res.data.merOrderId;
}


const MakeOrder = async()=>{
    const params = {
        merOrderId:state.preId,
        payType:state.payType,
        payMethod:'WAP',
    }

    const res:any = await makeOrder(params);
    const {flag,message} = res;
    if(flag!==1){
        uni.showToast({
            title: message,
            duration: 3000,
        });
        closeLoading();
        return 
    }

    console.log('MakeOrder')
    console.log('MakeOrder')
    console.log('MakeOrder')
    console.log(res);


    //state.orderId = res.data.payParam;
}



const openZhifubao = ()=>{
    //checkStatu();
    const merOrderId = state.preId;
    const payType = state.payType;
    const token = uni.getStorageSync('api_token');
    console.log('token')
    console.log(token)
    state.webview.evalJS(`init("${merOrderId}","${payType}","${token}")`);
    return true;

}

const openPayApp = async()=>{
    if(Number(state.payType)===1){
        uni.showToast({
            icon: "none",
            title: '暂不支持微信支付',
            duration: 3000,
        });
        closeLoading();
        return false;
    }
    if(Number(state.payType)===2){
       openZhifubao();
       return true;
    }
}

const checkStatu:any = async()=>{

    if(state.chancel){
        return Promise.reject('取消')
    }

    if(state.checkNum>=33){
        return Promise.reject('超时');
    }

    state.checkNum +=1;
    const res:any = await checkPayStatu({merOrderId:state.preId}).catch((err)=>{
        console.log('eeeeeeeeeeee')
        console.log('eeeeeeeeeeee')
        console.log('eeeeeeeeeeee')
        console.log(err)
    })

    if(!res){
        await wait(2000);

        return await checkStatu();
    }

    const {flag,message,data} = res;




    if(flag!==1){
        await wait(2000);

        return await checkStatu();
    }

    const { payStatus } = data;

    if(payStatus!==1){

        await wait(2000);
        return await checkStatu();

    }


    // uni.showToast({
    //         icon: "none",
    //         title: message||'支付成功!',
    //         duration: 3000,
    // });
    return Promise.resolve(true);
}


export const pay = async ( {slimType,totalAmt,productId,payType}:any)=>{
    init();
    const pages = getCurrentPages();
	const page = pages[pages.length - 1];
	const currentWebview = page.$getAppWebview();

    if(!currentWebview.children()[0]){
         uni.showToast({
            icon: "none",
            title: '支付渠道不存在！',
            duration: 3000,
        });
        return;
    }

    state.webview = currentWebview.children()[0]


    state.webview.loadURL('/hybrid/html/ali.html')

    await wait(500);
	//wv.setStyle({top:0,height:1,width:1})

    // let id1 = 'sdsdi3763ed'
    // let id2 = '1234'
    // let id3 = 'ccccccccc'
    // const token = uni.getStorageSync('api_token');
    // console.log('tokentokentoken')
    // console.log('tokentokentoken')
    // console.log('tokentokentoken')
    // console.log(token);

	// wv.evalJS(`init("${id1}","${id2}","${id3}","${token}")`);


    if(!slimType||!totalAmt||!productId||!payType){
        uni.showToast({
            icon: "none",
            title: '支付参数有误，请检查',
            duration: 3000,
        });
        return;
    }

    state.slimType = slimType;
    state.totalAmt = totalAmt;
    state.productId = productId;
    state.payType = payType;


    console.log('start AdvanceOrder')
    console.log('start AdvanceOrder')
    console.log('start AdvanceOrder')

    await AdvanceOrder();


    // console.log('start MakeOrder')
    // console.log('start MakeOrder')
    // console.log('start MakeOrder')

    // await MakeOrder();

    console.log('start openPayApp')
    console.log('start openPayApp')
    console.log('start openPayApp')
    const openResult = openPayApp();
    if(!openResult){
        return Promise.reject(false);
    }
    console.log('start checkStatu')
    console.log('start checkStatu')
    console.log('start checkStatu')
    const result = await checkStatu();
    return result

}

